package com.cqut.servlet;

import com.alibaba.fastjson.JSON;
import com.cqut.entity.student;
import com.cqut.entity.user;
import com.cqut.utils.DBUtils;
import com.cqut.utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ServletUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        String action = req.getParameter("action") == null ? "" : req.getParameter("action");
        switch (action) {
            case"getdglist":
                getDglist(req,resp);
                break;
            case"exists":
                Exists(req,resp);
                break;
            case"getone":
                getOne(req,resp);
                break;
            case"update":
                Update(req,resp);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //分页
    private void getDglist(HttpServletRequest req, HttpServletResponse resp) {

        try {
            //获取参数
            String pageIndex = req.getParameter("page") == null ? "1" : req.getParameter("page");
            String pageSize = req.getParameter("rows") == null ? "10" : req.getParameter("rows");

            // 将字符串转换为整数，并处理可能的异常
            int currentPage = Integer.parseInt(pageIndex);
            int pageSizeInt = Integer.parseInt(pageSize);

            // 确保页数和每页大小都是合理的值
            if (currentPage < 1) currentPage = 1;
            if (pageSizeInt < 1) pageSizeInt = 10;


            PrintWriter out = resp.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            // 获取总记录数
            String sqlcount = "select count(*) from user";
            int total = Integer.parseInt(DBUtils.QueryScalar(sqlcount).toString());
            map.put("total", total);
//            String sqllist ="SELECT * FROM student LIMIT 10";

            // 计算LIMIT子句的参数
            int offset = (currentPage - 1) * pageSizeInt;
            String sqllist = "SELECT * FROM ( " +
                    "  SELECT (@row_number:=@row_number + 1) AS rownumber, tmp_table.* " +
                    "  FROM ( SELECT * FROM user ORDER BY username ASC ) AS tmp_table, (SELECT @row_number:=0) AS t " +
                    ") AS tmp_table " +
                    "WHERE rownumber > " + offset + " " +
                    "LIMIT " + pageSize;

            //问题在这一句
            List<user> list = DBUtils.QueryBeanList(sqllist, user.class);

            map.put("rows", list);
            out.write(JSON.toJSONString(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //判断编码是否存在

    private void Exists(HttpServletRequest req, HttpServletResponse resp) {
        try{
            PrintWriter out = resp.getWriter();
            String sno = req.getParameter("username");
            String sql = "select count(*) from user where username = ?";
            int count = Integer.parseInt(DBUtils.QueryScalar(sql,sno).toString());
            if(count > 0){
//                out.write(JSON.toJSONString(new ResultData("200","数据已经存在")));
                out.write("false");
            }
            else
                out.write("true");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取选择行数据
    private void getOne(HttpServletRequest req, HttpServletResponse resp) {
        try{
            PrintWriter out = resp.getWriter();
            String username = req.getParameter("username");
            String sql = "select * from user where username = ?";
            user user = DBUtils.QueryBean(sql, user.class,username);
            ResultData rd = new ResultData();
            if(user != null){
                rd.setCode(String.valueOf(resp.getStatus()));
                rd.setMsg("获取成功");
                rd.setData(user);
                out.write(JSON.toJSONString(rd));
            }
            else{
                rd.setCode("501");
                rd.setMsg("获取失败");
                out.write(JSON.toJSONString(rd));
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    //修改行数据
    private void Update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try{
            PrintWriter out = resp.getWriter();
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            String sql = "update user set password=? where username = ?";
            if(DBUtils.Update(sql,password,username) > 0){
                out.write(JSON.toJSONString(new ResultData(String.valueOf(resp.getStatus()),"保存成功")));
            }
            else{
                out.write(JSON.toJSONString(new ResultData("501","保存失败")));
            }

        }catch (Exception e) {
            resp.getWriter().write(JSON.toJSONString(new ResultData("501","数据有误")));
        }
    }

}
